﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;

namespace Brjnk.Maps.Downloader
{

    public class PriorityQueue<T>
    {
        ConcurrentQueue<T>[] queues;

        IPriorities priorities;

        public PriorityQueue(IPriorities priorities)
        {
            queues = new ConcurrentQueue<T>[priorities.PrioritiesCount];
            this.priorities=priorities;
            for(int i=0;i<priorities.PrioritiesCount;i++)
            {
                queues[i]=(new ConcurrentQueue<T>());
            }
        }

        public void Add(T item)
        {
            if((object)item ==null)throw new ArgumentNullException("Null (nothing) cannot be inserted to queue!");
            queues[priorities.GetPriorityNumber(item)].Enqueue(item);
        }

        /// <summary>
        /// Odebere z fronty jeden objekt, nebo vrátí default(T), pokud není dostupný
        /// </summary>
        /// <returns></returns>
        public T  Dequeue(out bool success)
        {
            for (int i = 0; i < queues.Length; i++)
            {
                T item;
                if (queues[i].TryDequeue(out item))
                {
                    success = true;
                    return item;
                }
            }
            success = false;
            return default(T);
        }

    }
}
